<template>
<el-upload
  :action="uploadUri"
  :multiple="multiple"
  :limit="limit"
  :headers="headers"
  :show-file-list="showFileList"
  :with-credentials="withCredentials"
  :on-success="uploadSuccess"
  :on-progress="onUploading"
  :before-upload="beforeUpload">
  <template v-if="showFileList && fileDatas && fileDatas.length > 0">
    <template v-for="item in fileDatas">
      <template v-if="showPreview">
        <img :src="`${loadUri}?fileId=${item.fileId}`" :alt="item.fileName">
      </template>
      <template v-else>
        <img :src="fileTypes[item.extensionName]" :alt="item.fileName">
      </template>
    </template>
  </template>
  <template v-else>
    <i class="el-icon-upload"></i>
    <div>点击上传</div>
    <div class="el-upload__tip" slot="tip">上传文件不可超过{{size}}kb</div>
  </template>
</el-upload>
</template>
<script>
export default {
  model: {
    prop: "value",
    event: "uploaded"
  },
  props:{
    value: {
      type: Array,
      default() {
        return []
      }
    },
    multiple: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 1
    },
    showFileList:{
      type: Boolean,
      default: false
    },
    showPreview: {
      type: Boolean,
      default: false
    },
    withCredentials:{
      type: Boolean,
      default: true
    },
    group:{
      type: String,
      default: 'dmc'
    },
    path: {
      type: String,
      default: '/'
    },
    size:{
      type: Number,
      default: 512
    },
    mimeTypes:{
      type: Array,
      default() {
        return []
      }
    }
  },
  data(){
    return {
      fileDatas:[],
      fileTypes: {
        ".rar": require("@/assets/img/rar.png"),
        ".7z": require("@/assets/img/zip.png"),
        ".zip": require("@/assets/img/zip.png"),
        ".pdf": require("@/assets/img/pdf.png"),
        ".jpg": require("@/assets/img/pic.png"),
        ".jpeg": require("@/assets/img/pic.png"),
        ".gif": require("@/assets/img/pic.png"),
        ".bmp": require("@/assets/img/pic.png"),
        ".ico": require("@/assets/img/pic.png"),
        ".png": require("@/assets/img/pic.png"),
        ".doc": require("@/assets/img/doc.png"),
        ".docx": require("@/assets/img/docx.png"),
        ".xls": require("@/assets/img/xls.png"),
        ".xlsx": require("@/assets/img/xlsx.png"),
        ".ppt": require("@/assets/img/ppt.png"),
        ".pptx": require("@/assets/img/ppt.png"),
        ".txt": require("@/assets/img/txt.png"),
        ".json": require("@/assets/img/txt.png"),
        ".xml": require("@/assets/img/txt.png"),
      }
    }
  },
  computed: {
    uploadUri(){
      return `${this.$service.storage.upload}/${this.group}?path=${this.path}` ;
    },
    loadUri(){
      return `${this.$service.file.load}/${this.group}`;
    },
    headers(){
      return {
        Authorization: `Bearer ${this.$store.state.token}`
      }
    },
    fileIds: {
      get(){
        return this.value;
      },
      set(val){
        this.$emit('uploaded', val);
      }
    }
  },
  watch: {
    value: {
      handler(nVal, oVal) {
        if (nVal && nVal.length > 0 && JSON.stringify(nVal) !== JSON.stringify(oVal)){
          this.query(nVal)
        }
      },
      deep: true
    }
  },
  mounted(){
  },
  methods:{
    query(){
      this.$service.file.getFiles({ routeData: { group: this.group }, data: this.fileIds}).then(r => {
        if(r.success && r.data) {
          let files = [];
          let ids = [];
          r.data.forEach(item => {
            files.push(item.fileData);
            ids.push(item.fileData.fileId);
          });
          this.fileDatas = files;
          this.fileIds = ids;
        }
      });
    },
    beforeUpload(file){

      return new Promise((resolve, reject) => {
        const validType = this.mimeTypes == null || this.mimeTypes.length <= 0 || this.mimeTypes.any(t => t === file.type);
        const validLen = file.size / 1024 < this.size;

        if (!validType) {
          alert(`上传格式只能是 ${this.mimeTypes.join(',')} 格式!`);
          reject();
        }
        if (!validLen){
          alert(`上传文件不可超过${this.size}KB！`, "提示", "warning");
          reject();
        }
        else{
          this.$service.file.checkFile({
            routeData: {group: this.group},
            data:{path: this.path, fileName: file.name}
          }).then((r)=>{
            if (r.success){
              resolve();
            }
            else{
              confirm(`文件${file.name}已经存在，要覆盖吗？`, "提示", "info", ()=>{
                resolve();
              }, reject);
            }
          }).catch(reject);
        }

      });
    },
    uploadSuccess(response, file, fileList){
      if(response.success && response.data) {
        if (this.multiple){
          this.fileDatas = [... this.fileDatas, response.data];
          this.fileIds = [... this.fileIds, response.data.select(t => t.fileId)];

        }
        else{
          this.fileDatas = response.data;
          this.fileIds = response.data.select(t => t.fileId);
        }

        this.$emit('onSuccess', response);
      }

    },
    onUploading(event, file, fileList){

    },
    getFileList(){
      return this.fileDatas;
    }
  }
}
</script>
